package study.thread.cas;


public class CasCounter {
	private SimulatedCAS value = new SimulatedCAS(0);

	public int getValue() {
		return value.getValue();
	}

	public int increment() {
		int oldValue = value.getValue();
		while (value.compareAndSwap(oldValue, oldValue + 1) != oldValue)
			oldValue = value.getValue();
		return oldValue + 1;
	}
	
	public static void main(String[] args) throws InterruptedException{
		 
		final CasCounter casCounter = new CasCounter();
		
		Thread[] ts = new Thread[10];
		
		for (int i = 0; i < 10; i++) {
			ts[i] = new Thread(){
				
				public void run() {
					casCounter.increment();
					System.out.println("Thread"+Thread.currentThread().getName()+"====> "+casCounter.getValue());
					System.exit(0);
				}
			};
		}
		
		for (int i = 0; i < ts.length; i++) {
			ts[i].start();
			ts[i].join();
		}
		
		System.out.println("value====> "+casCounter.getValue());
	}
}
